open BUFF,"<New_Clinical_data_filtered_recurrence_removed.txt" or die "no file exists\n";
open WRBUFF,">PARSED_CLINICALDATA";
$line=<BUFF>;
chomp($line);
print WRBUFF $line."\t"."Calc_AGE\tCalc_survivaltime\tCalc_survivalEvent\tClac_sex\n";
@array = split("\t",$line);
for($i=0;$i<@array;$i++)
{
	if($array[$i]  eq "Birth Date")
	{
		$index_birthday = $i;
	}
	if($array[$i]  eq "Death Date")
        {
                $index_deathday = $i;
        }
	if($array[$i]  eq "Diagnosis Date")
        {
                $index_diagnosisday = $i;
        }
	if($array[$i]  eq "Gender")
        {
                $index_sex = $i;
        }
	if($array[$i]  eq "Alive Status")
        {
                $index_status = $i;
        }
	if($array[$i]  eq "Last Followup Date")
	{
                $index_follow = $i;
        }

}
#print "$index_birthday\t$index_deathday\t$index_diagnosisday\t$index_sex\t$index_status\n";
while(<BUFF>)
{
	chomp($_);
	@array = split(/\t/,$_);
	if($array[$index_follow] ne "null" && $array[$index_diagnosisday] ne "null" && $array[$index_birthday] )
	{

#status
		if($array[$index_status] eq "Yes")
		{
			$status = 0;
			#patients who are not alive , follow up date is equal to death date
		}
		else
		{
			$status = 1;
		}
	#sex	
		if($array[$index_sex] eq "Male")
        	{
                	$sex =1;
        	}
        	else
        	{
                	$sex =2;
        	}
	#age
		@start = split(/\//,$array[$index_birthday]);
        #	patients who are not alive , follow up date is equal to death date
        	@stop=split(/\//,$array[$index_follow]);
		$age = $stop[2]-$start[2];
        	if(!($stop[1] >= $start[1] && $stop[0] >= $start[0]))
        	{
                	$age = $age-1;
        	}
	#survival time
		@start = split(/\//,$array[$index_diagnosisday]);
		$survivaltime = (($stop[2])*12+$stop[0])-(($start[2])*12+$start[0]);
		 if(!($stop[1] >= $start[1]))
		{
			$survivaltime = $survivaltime-1;
		}	
		print WRBUFF $_."\t$age\t$survivaltime\t$status\t$sex\n";
	}
}
system("Rscript parse_clinical_residuals.R");
system("mv PARSED_CLINICALDATA_NEW PARSED_CLINICALDATA");
